/**
 ************************************************************************
  > File Name: controllers/sign.js
  > Author: Leeiio <iio@iiobox.com>
  > Site: https://www.iiobox.com
  > Created Time: 08/04/17 15:25:24
 ************************************************************************/

var Eventproxy = require('eventproxy');
var User = require('../proxy').User;
var tools = require('../common/tools');
var config = require('config-lite');
var logger = require('../common/logger');
var models = require('../models');
var authMiddleWare = require('../middlewares/auth');
var uuidV4 = require('uuid/v4');

var logger = require('../common/logger');
var validator = require('validator');

// 获取登录授权码
exports.getAccessToken = function getAccessToken(req, res) {
  var requestAgent = req.get('Request-Agent') || 'web';
  var data = req.body;
  if (!data.pcode) {
    return res.send_data({
      code: 400,
      message: '缺少pcode参数'
    });
  }

  data.pcode += '';

  var pcode = data.pcode.trim();
  models.user.findOne({
    where: {
      pcode: data.pcode
    },
    include: [{
      model: models.event
    }]
  }).then(function (user) {
    if (!user) {
      return res.send_data({
        code: 401,
        message: 'wrong pcode'
      });
    }

    if (user && user.plevel === config.plevels[3] && requestAgent === 'web') {
      return res.send_data({
        code: 401,
        message: 'You don\' have permission'
      });
    }

    if (user && !user.status) {
      return res.send_data({
        code: 401,
        message: 'The user has been suspended'
      });
    }
    if (user && user.event && !user.event.status) {
      return res.send_data({
        code: 401,
        message: 'The event has been suspended'
      });
    }
    var _user = user.toJSON();
    _user.event_name = _user.event ? _user.event.name : 'SportsABC';
    _user.event_sdate = _user.event ? _user.event.sdate : '';
    _user.event_edate = _user.event ? _user.event.edate : '';
    delete _user.event;
    var plevel = user.plevel;
    var str = plevel + ':' + pcode;
    var accessToken = tools.encrypt(str, config.admin_secret);
    return res.send_data({
      entities: {
        access_token: accessToken,
        user: _user
      }
    });
  });
};

// 生成一个uuid
exports.genUUID = function genUUID(req, res) {
  return res.send_data({
    data: {
      uuid: uuidV4()
    }
  });
};
